package com.spring.web.adminmanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spring.web.adminmanage.common.PageResult;
import com.spring.web.adminmanage.entities.UserLoginLog;
import com.spring.web.adminmanage.repository.UserLoginLogDao;
import com.spring.web.adminmanage.service.UserLoginLogService;
import com.spring.web.adminmanage.utils.DateFormatUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserLoginLogServiceImpl extends BaseServiceImpl<UserLoginLog> implements UserLoginLogService {
	
	@Autowired
	UserLoginLogDao userLoginLogDao;
	
	@Override
	public void addLoginLog(Long userid,String remoteAddr) {
		if ("0:0:0:0:0:0:0:1".equals(remoteAddr)) {
			remoteAddr="127.0.0.1";
		}
		UserLoginLog ulLog = new UserLoginLog(userid, remoteAddr, new Date());
		userLoginLogDao.insert(ulLog);
	}

	@Override
	public PageResult<UserLoginLog> selectToPageResult(Integer pageSize, Integer pageNumber, String username, String ip,
													   String queryTimeRange) {
		Date queryStartDate = null;
    	Date queryEndDate =  null;
		try {
			if(StringUtils.isNotBlank(queryTimeRange)) {
				String[] dateArrays = queryTimeRange.split("~");
				queryStartDate = DateFormatUtil.parseDate(dateArrays[0].trim(), 1);
				queryEndDate = DateFormatUtil.appendDate(DateFormatUtil.parseDate(dateArrays[1].trim(), 1), 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageHelper.startPage(pageNumber,pageSize);
		PageInfo<UserLoginLog> pageinfo = new PageInfo<UserLoginLog>(userLoginLogDao.selectList(username,ip,queryStartDate,queryEndDate));
		return new PageResult<UserLoginLog>(pageinfo);
	}
}